<template>
    <div class="container">
        <a-row>
            <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <a-space>
                    <a-input v-model:value="name"></a-input>
                    <a-button type="primary" @click="findKeywords">查询</a-button>
                    <a-button type="primary" @click="addOpen">添加</a-button>
                    <h1>
                        剩余点数：{{ 200000 - value }}
                    </h1>
                </a-space>
            </a-col>
            <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" style="margin-top: 10px;">
                <a-table :columns="columns" :dataSource="tableData" :scroll="{ y: 500 }" size="small" rowKey="id"
                    :rowSelection="{}">
                    <template #bodyCell="{ record, column }">
                        <template v-if="column.key === 'option'">
                            <a-input-number :disabled="record.points === 0" v-model:value="record.limit"
                                @change="increase" min="0"></a-input-number>
                        </template>
                        <template v-if="column.key === 'action'">
                            <a-space>
                                <a-button type="link" @click="edit(record)">编辑</a-button>
                                <a-button danger type="link">删除</a-button>
                            </a-space>
                        </template>
                    </template>
                </a-table>
                <a-divider type="vertical" />
                <h1>结算：{{ value }}</h1>
            </a-col>
        </a-row>
        <a-modal :open="open" :title="formState.id ? '修改' : '添加'" wrap-class-name="full-modal" @cancel="handleCancel"
            name="custom-validation">
            <a-form ref="formRef" :model="formState" :label-col="{ span: 4 }" :wrapper-col="{ span: 16 }">
                <a-form-item label="父级" name="parent">
                    <a-select v-model:value="formState.parent" allowClear @change="onSearch">
                        <a-select-option :value="item.id" v-for="(item, index) in parentList" :key="index"
                            :disabled="item.id === formState.id">{{ item.name
                            }}</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item label="名称" name="name" :rules="[{ required: true, message: '请输入名称!' }]">
                    <a-input v-model:value="formState.name" />
                </a-form-item>
                <a-form-item label="点数" name="points" :rules="[{ required: true, message: '点数不能为空!' }]">
                    <a-input v-model:value="formState.points" type="number" />
                </a-form-item>
            </a-form>
            <template #footer>
                <a-button key="back" @click="handleCancel">取消</a-button>
                <a-button type="primary" @click="handleOk">确定</a-button>
            </template>
        </a-modal>
    </div>
</template>

<script setup lang="ts">
import { getMaterialsList, getMaterialsParent, findMaterialsKeywords, createMaterials, updateMaterials } from './api'
import { onMounted, reactive, ref, toRaw } from 'vue';
import { MinusOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { TreeUtils } from '@/utils'
import type { FormInstance } from 'ant-design-vue';
interface FormState {
    name: string;
    points: string;
    parent?: number | null;
    id?: number
}
interface FlatItem {
    id: number;
    parent?: number;
    // 其他可能的属性
    [key: string]: any;
}



let formState = reactive<FormState>({
    name: '',
    points: '',
    parent: null,
});
const formRef = ref<FormInstance>();
const name = ref('')
const value = ref(0)
let tableData = ref<FlatItem[]>([])
let parentList = ref<FlatItem[]>([])
const open = ref(false)
const columns = [
    {
        title: '名称',
        dataIndex: 'name',
        key: 'name',
    },
    {
        title: '点数',
        dataIndex: 'points',
        key: 'points',
        sorter: {
            compare: (a: any, b: any) => a.points - b.points,
            multiple: 3,
        },
    },
    {
        title: '数量',
        key: 'option',
    },
    {
        title: '操作',
        key: 'action',
    },
]
onMounted(() => {
    getMaterials()
    getParentList()
})

const getParentList = async () => {
    const res = await getMaterialsParent()
    parentList.value = res.data
}

const getMaterials = async () => {
    const res = await getMaterialsList()
    tableData.value = TreeUtils.toTree(res.data)
    console.log(tableData.value)
}

const findKeywords = async () => {
    const res = await findMaterialsKeywords(name.value)
    tableData.value = TreeUtils.toTree(res.data)
}

const handleOk = async () => {
    formRef.value
        .validate()
        .then(async () => {
            if (formState.id) {
                await updateMaterials(formState.id,toRaw(formState))
            } else {
                await createMaterials(toRaw(formState))
            }
            getMaterials()
            getParentList()
            formState = {
                name: '',
                points: '',
                parent: null,
            }
            open.value = false
        })
        .catch((error: any) => {
            console.log('error', error);
        });
}

const addOpen = () => {
    open.value = true
}

/**
 * 取消操作的处理函数。
 * 重置表单字段并将弹窗状态设置为关闭。
 */
const handleCancel = () => {
    formState = {
        name: '',
        points: '',
        parent: null,
    }
    open.value = false;
}

const edit = (column: any) => {
    formState = JSON.parse(JSON.stringify(column))
    open.value = true
}
const increase = () => {
    value.value = 0
    tableData.value.forEach((item) => {
        if (item.children) {
            item.children.forEach((_item: any) => {
                value.value += _item.limit * _item.points
            })
        }
        value.value += item.limit * item.points
    })
}
const onSearch = (value: string) => {
    console.log(formState)
    if (!value) formState.parent = null
}
</script>

<style scoped>
.container {
    width: 100%;
    height: 100%;
    padding: 10px;
    background-color: #fff;
}
</style>